<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Edit, Plus, Search} from '@element-plus/icons-vue'
import http from "@/request/Http.js";

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const multipleSelection = ref([])

// 搜索相关
const searchForm = reactive({
  name: ''
})

// 分页相关
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格列配置（仅保留需要的列）
const columns = [
  {
    type: 'index',       // 序号列（Element Plus 内置的索引列）
    label: '序号',
    width: '60',
    align: 'center'
  },
  {
    prop: 'name',       // 分类名称列
    label: '名称',
    width: '200'
  },
  {
    prop: 'createdAt',  // 创建时间列
    label: '创建时间',
    width: '180',
    formatter: (row) => formatDate(row.createdAt) // 格式化时间（需和下方方法对应）
  },
  {
    label: '操作',       // 操作列（固定右侧）
    width: '200',
    fixed: 'right',
    slotName: 'operation' // 对应 <el-table-column> 的 #default 插槽名（下面会改）
  }
];

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    const response = await http.get('/classify/getCategories', {
      params: {
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        name: searchForm.name,
      }
    });

    console.log(response)
    if (response.code === 200) {
      const pageData = response.data;

      tableData.value = pageData.records?.map(item => ({
        ...item
      })) || [];

      pagination.total = pageData.total || 0;
    } else {
      ElMessage.error(response.msg || '获取数据失败');
    }
  } catch (error) {
    ElMessage.error('获取数据失败，请检查网络或联系管理员');
    console.error('API Error:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getTableData()
}

// 重置搜索
const handleReset = () => {
  searchForm.name = ''
  pagination.currentPage = 1
  getTableData()
}

// 控制新增弹窗的显示与隐藏
const addDialogVisible = ref(false)

const addForm = reactive({
  name: '',
  description: ''
})

// 表单校验规则
const addFormRules = {
  name: [
    {required: true, message: '请输入分类名称', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
  ],
  description: [
    {max: 500, message: '描述不能超过500个字符', trigger: 'blur'}
  ]
}

// 打开新增对话框
const handleAdd = () => {
  addDialogVisible.value = true
}

// 提交新增表单
const submitAddForm = async () => {
  try {
    const response = await http.post('/classify/addCategories', addForm)
    if (response.code === 200) {
      ElMessage.success('新增分类成功')
      addDialogVisible.value = false
      // 重置表单
      Object.assign(addForm, {
        name: '',
        description: ''
      })
      // 刷新表格数据
      getTableData()
    } else {
      ElMessage.error(response.msg || '新增失败')
    }
  } catch (error) {
    console.error('新增分类失败:', error)
    ElMessage.error('新增分类失败，请检查网络或联系管理员')
  }
}

// 取消新增，关闭弹窗
const cancelAdd = () => {
  addDialogVisible.value = false
  // 重置表单
  Object.assign(addForm, {
    name: '',
    description: ''
  })
}

// 批量删除
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${multipleSelection.value.length} 条数据吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    // 提取选中行的 ID 数组
    const ids = multipleSelection.value.map(row => row.id)

    // 调用批量删除接口
    const response = await http.post('/classify/deleteAllCategories', ids)

    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      getTableData()
    } else {
      ElMessage.error(response.msg || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 单行删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除分类 "${row.name}" 吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    // 调用删除API
    const response = await http.delete(`/classify/deleteCategories/${row.id}`)

    if (response.code === 200) {
      ElMessage.success('删除成功')
      getTableData()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 控制编辑弹窗的显示与隐藏
const editDialogVisible = ref(false)

// 编辑表单，与 addForm 类似，但是用来回显和提交修改
const editForm = reactive({
  id: null,
  name: '',
})

// 引用编辑表单的 ref，用于调用 validate 方法
const editFormRef = ref()

// 表单校验规则（与新增类似）
const editFormRules = {
  name: [
    {required: true, message: '请输入分类名称', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
  ]
}

// 显示原来的数据
const handleEdit = (row) => {
  // 回显选中行的数据到 editForm
  Object.assign(editForm, {
    id: row.id,
    name: row.name || ''
  })
  editDialogVisible.value = true
}

// 提交编辑表单
const submitEditForm = async () => {
  if (!editFormRef.value) return

  try {
    // 先校验表单
    await editFormRef.value.validate()

    const response = await http.put('/classify/updateCategories', editForm)

    if (response.code === 200) {
      ElMessage.success('修改成功')
      editDialogVisible.value = false
      getTableData() // 刷新表格
    } else {
      ElMessage.error(response.msg || '修改失败')
    }
  } catch (error) {
    if (error !== false) { // 非校验失败时打印错误
      console.error('编辑提交失败:', error)
      ElMessage.error('修改失败，请检查网络或联系管理员')
    }
    // 表单校验失败时，不会进入此 catch，而是停留在校验提示
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getTableData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getTableData()
}

// 格式化日期函数（将 Date 或时间字符串格式化为可读形式）
const formatDate = (date) => {
  if (!date) return '无'; // 如果日期为空，显示 '无'

  let d;
  // 如果 date 是字符串，尝试转换为 Date 对象
  if (typeof date === 'string') {
    // 尝试常见的日期字符串格式，比如后端返回的 "2024-06-01T12:00:00.000+00:00" 或时间戳字符串
    d = new Date(date);
  } else if (date instanceof Date) {
    d = date;
  } else {
    // 其他情况（比如数字时间戳），也尝试转换
    d = new Date(date);
  }

  // 检查是否是有效的日期对象
  if (isNaN(d.getTime())) {
    return '无效时间';
  }

  // 格式化日期为 YYYY-MM-DD HH:mm:ss（可根据需求调整）
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 组件挂载时获取数据
onMounted(() => {
  getTableData()
})
</script>

<template>
  <div class="category-manage">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="searchForm.name"
          class="search-input"
          clearable
          placeholder="请输入分类名称"
      >
        <template #prefix>
          <el-icon>
            <Search/>
          </el-icon>
        </template>
      </el-input>
      <el-button :icon="Search" type="primary" @click="handleSearch">
        搜索
      </el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 操作按钮栏 -->
    <div class="action-buttons">
      <el-button :icon="Plus" type="primary" @click="handleAdd">
        新增分类
      </el-button>
      <el-button
          :disabled="multipleSelection.length === 0"
          :icon="Delete"
          type="danger"
          @click="handleBatchDelete"
      >
        批量删除 ({{ multipleSelection.length }})
      </el-button>
    </div>

    <!-- 新增分类弹窗 -->
    <el-dialog
        v-model="addDialogVisible"
        :before-close="cancelAdd"
        title="新增分类"
        width="500px"
    >
      <el-form :model="addForm" :rules="addFormRules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入分类名称"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑分类弹窗 -->
    <el-dialog
        v-model="editDialogVisible"
        :before-close="() => { editDialogVisible = false }"
        title="编辑分类"
        width="500px"
    >
      <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="80px"
      >
        <el-form-item label="分类ID" prop="id">
          <el-input v-model="editForm.id" disabled placeholder="分类ID"/>
        </el-form-item>

        <el-form-item label="分类名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入分类名称"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 数据表格 -->
    <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <!-- 选择框（可选，如不需要可删除） -->
      <el-table-column align="center" type="selection" width="50"/>

      <!-- 序号 -->
      <el-table-column
          align="center"
          label="序号"
          width="60"
      >
        <template #default="{ $index }">
          <div
              class="sortable-index"
              @click="handleSortByIndex"
          >
            {{ $index + 1 }}
          </div>
        </template>
      </el-table-column>

      <!-- 分类名称 -->
      <el-table-column label="名称" min-width="120" prop="name">
        <template #default="{ row }">
          <el-tag type="primary">{{ row.name }}</el-tag>
        </template>
      </el-table-column>

      <!-- 创建时间 -->
      <el-table-column label="创建时间" prop="createdAt" width="180">
        <template #default="{ row }">
          <div class="time">{{ formatDate(row.createdAt) }}</div>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column
          align="center"
          fixed="right"
          label="操作"
          width="160"
      >
        <template #default="{ row }">
          <el-button
              :icon="Edit"
              link
              size="small"
              type="primary"
              @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
              :icon="Delete"
              link
              size="small"
              type="danger"
              @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style scoped>
.category-manage {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-sizing: border-box;
  width: 100%; /* 确保容器撑满父级 */
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.description {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

.time {
  font-size: 12px;
  color: #888;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    margin-right: 0;
    margin-bottom: 10px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }

  .pagination-container {
    justify-content: center;
  }
}
</style>